package com.ruix.app.ui.stratum;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.desmond.parallaxviewpager.ExpandableListViewFragment;
import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ClassCourseMapper;
import com.ruix.app.model.ClassCourse;
import com.ruix.app.model.Classes;
import com.ruix.app.model.Lesson;
import com.ruix.app.network.CacheObserver;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.network.exception.NetworkUnusableException;
import com.ruix.app.network.exception.RequestApiException;
import com.ruix.app.network.exception.TokenExpiredException;
import com.ruix.app.ui.adapter.CourseListAdapter;
import com.ruix.app.ui.stratum.lesson.CaseLearningActivity;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.ToastUtil;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import io.reactivex.disposables.Disposable;


/**
 * 案例学习
 */
public class CaseLearningViewFragment extends ExpandableListViewFragment implements ExpandableListView.OnChildClickListener,CourseListAdapter.SortListener{

    public static final String TAG = CaseLearningViewFragment.class.getSimpleName();

//    private LinearLayoutManager mLayoutMgr;
    private Classes currentClasses;
//    private SpringView springView;
//    private TextView courseNumView, courseSortBtn;

//    private ClassCourse classCourse;
    private CourseListAdapter adapter;
//    private boolean desc; //// TODO: 2017/5/9
    private boolean isRefershing;

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (RuiXConstant.NOTICE_CASE_REFRESH.equals(intent.getAction())) {
                loadCourseList(adapter.isDesc(),true);
            }
        }

    };


    public static Fragment newInstance(int position, Classes classes) {
        CaseLearningViewFragment fragment = new CaseLearningViewFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_POSITION, position);
        args.putSerializable("classes", classes);
        fragment.setArguments(args);
        return fragment;
    }

    public CaseLearningViewFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mPosition = getArguments().getInt(ARG_POSITION);
        currentClasses = (Classes) getArguments().getSerializable("classes");

        View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);

//        springView = (SpringView) view.findViewById(R.id.spring_view);
        mExpandableListView = (ExpandableListView) view.findViewById(R.id.expand_list_view);

        View footerView = View.inflate(this.getContext(), R.layout.item_course_list_footer, null);

        View placeHolderView = inflater.inflate(R.layout.header_placeholder, mExpandableListView, false);

//        courseNumView = (TextView) headerView.findViewById(R.id.tv_course_num);
//        courseSortBtn = (TextView) headerView.findViewById(R.id.btn_sort_list);
        setListViewOnScrollListener();
        mExpandableListView.setGroupIndicator(null);
        mExpandableListView.addHeaderView(placeHolderView);
        mExpandableListView.addFooterView(footerView);
//        courseSortBtn.setOnClickListener(this);

        mExpandableListView.setOnChildClickListener(this);
        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });

//        expandableListView.setOnGroupCollapseListener(this);
//        expandableListView.setOnGroupExpandListener(this);

        adapter = new CourseListAdapter(this.getActivity());
        adapter.setDesc(false);
        adapter.setListener(this);
        mExpandableListView.setAdapter(adapter);
        registerReceivers();

        loadCourseListByCache();
        loadCourseList(false,false);


        return view;
    }





    private void loadCourseList(final boolean desc, final boolean refresh) {
       if (currentClasses == null){
           if (refresh){
               onFinishToRefresh();
           }
           return;
       }

        RequestFactory.getCourseList(currentClasses.getID(),desc, new ClassCourseMapper(), new RXObserver<ClassCourse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ClassCourse value) {
                if (value != null){
                    value.setDesc(desc);
                    updateView(value);
                    if (!desc) { //缓存正序
                        CacheFactory.cacheCourseList(currentClasses.getID(), value);
                    }

                    if (refresh){
                        onFinishToRefresh();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                if (refresh){
                    onFinishToRefresh();
                }
                resolveException(e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void updateView(ClassCourse value){
        adapter.setCourseInfo(value.getCouseNumInfo());
        adapter.setDesc(value.isDesc());
        adapter.setCourses(value.getCourses());
//        courseNumView.setText("课程"+value.getCurrentLesson()+"/"+value.getTotalLesson());
        expandGroup();
    }


    private void expandGroup(){
        for (int i = 0; i < adapter.getGroupCount(); i++) {
            mExpandableListView.expandGroup(i);
        }
    }


    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        Lesson lesson = adapter.getChild(groupPosition,childPosition);
        UserManager.sharedInstance().setCurrentLesson(lesson);
        getActivity().startActivity(CaseLearningActivity.newIntent(getActivity(),lesson,currentClasses,null));
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceivers();
    }

    @Override
    public void sortCourse(boolean desc) {
        loadCourseList(!desc,false);
    }


    public void loadCourseListByCache(){
        if (currentClasses == null){
            return;
        }
        CacheFactory.loadCourseList(currentClasses.getID(),new CacheObserver<ClassCourse>(){
            @Override
            public void onNext(ClassCourse value) {
                if (value != null){
                    updateView(value);
                }

            }

        });

    }

    public void onFinishToRefresh() {
        isRefershing = false;
        Intent intent = new Intent(RuiXConstant.NOTICE_MOMENTS_REFRESH_FINISH);
        RuiApplication.getAppContext().sendBroadcast(intent);
    }

    private void registerReceivers() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(RuiXConstant.NOTICE_CASE_REFRESH);
        getContext().registerReceiver(myReceiver, filter);
    }

    private void unregisterReceivers() {
        if (myReceiver != null) {
            getContext().unregisterReceiver(myReceiver);
        }
    }

    public void resolveException(Throwable e) {
        if (e instanceof SocketTimeoutException) {
            showErrorTip("网络不通");
        } else if (e instanceof UnknownHostException) { //解析不到域名 网络不通
            showErrorTip("网络不通");
        } else if (e instanceof NetworkUnusableException) { // 网络不可用，比如WiFi断开
            showErrorTip("网络不通");
        } else if (e instanceof IOException) { //socket 超时 网络超时 SocketTimeoutException
            showErrorTip("网络不通");
        } else if (e instanceof TokenExpiredException) { //重新登录
            Intent intent = new Intent();
            intent.setAction(RuiXConstant.NOTICE_LOGOUT);
            RuiApplication.getAppContext().sendOrderedBroadcast(intent, null);
        } else if (e instanceof RequestApiException) {
            showErrorTip(e.getMessage());
        } else {

        }
    }

    public void showSuccessTip(String msg) {
        ToastUtil.showNewSuccessMsg(msg);
    }


    public void showErrorTip(String msg) {
        ToastUtil.showNewErrorMsg(msg);
    }
}
